#!/bin/sh

# This a hand-crafted, experimental, and, well, uncommented configure script.
# Your feedback will be appreciated.

for arg in "$@"
do
    case $arg in
        -h | --h | -help | --help )
            echo "Usage:"
            echo "    $0 [options]"
            echo "Options:"
            echo "    -h, -help               Show this help"
            echo "    -with-system-zlib       Use the system-supplied zlib"
            echo "    -with-system-libpng     Use the system-supplied libpng"
            echo "Environment variables:"
            echo "    CC                      C compiler command"
            exit 0
            ;;
        -with-system-zlib | --with-system-zlib )
            with_system_zlib=1
            ;;
        -with-system-libpng | --with-system-libpng )
            with_system_libpng=1
            ;;
        * )
            echo "Unknown option: $1"
            echo "Type \"$0 -help\" for help"
            exit 1
            ;;
    esac
done

if test "$with_system_zlib"
then
    zlib_inc_del='s:\(.\)-I\$(ZDIR):\1:g'
    zlib_lib_del='s:\(.\)\$(ZDIR)/\$(ZLIB):\1:g'
    zlib_sys_ins='/^SYSLIBS *=/s:$: -lz:'
fi
if test "$with_system_libpng"
then
    libpng_inc_del='s:\(.\)-I$(PNGDIR):\1:g'
    libpng_lib_del='s:\(.\)$(PNGDIR)/$(PNGLIB):\1:g'
    libpng_sys_ins='/^SYSLIBS *=/s:$: -lpng:'
fi
if test "${zlib_sys_ins}${libpng_sys_ins}"
then
    sed -e "$zlib_inc_del" -e "$libpng_inc_del" \
        -e "$zlib_lib_del" -e "$libpng_lib_del" \
        -e "$zlib_sys_ins" -e "$libpng_sys_ins" \
        src/scripts/unix.mak.in > src/scripts/unix.mak
    sed -e "$zlib_inc_del" -e "$libpng_inc_del" \
        -e "$zlib_lib_del" -e "$libpng_lib_del" \
        -e "$zlib_sys_ins" -e "$libpng_sys_ins" \
        src/scripts/gcc.mak.in > src/scripts/gcc.mak
else
    cp -f -p src/scripts/unix.mak.in src/scripts/unix.mak
    cp -f -p src/scripts/gcc.mak.in src/scripts/gcc.mak
fi

test=hello$$
cat > $test.c <<EOM
int hello() { return 42; }
EOM

test -z "$CC" && echo "Checking for gcc..."
cc="${CC-gcc}"
case "$cc" in
    *gcc* ) gcc=1;;
esac
if test "$gcc" && ($cc -c $cflags $test.c) 2>/dev/null
then
    CC="${CC-gcc}"
    makefile=scripts/gcc.mak
else
    CC="${CC-cc}"
    makefile=scripts/unix.mak
fi
rm -f $test.c $test.o

sed -e "s:@MAKEFILE@:${makefile}:g" -e "s:@CC@:${CC}:g" \
    Makefile.in > Makefile
sed -e "s:@MAKEFILE@:${makefile}:g" -e "s:@CC@:${CC}:g" \
    src/Makefile.in > src/Makefile

if test -z "$with_system_zlib"
then
    echo "Configuring zlib..."
    (cd lib/zlib && ./configure)
    if test $? -ne 0
    then
        echo "Could not configure: zlib"
        exit 1
    fi
fi
#if test -z "$with_system_libpng"
#then
#    echo "Configuring libpng..."
#    (cd lib/libpng && ./configure)
#    if test $? -ne 0
#    then
#        echo "Could not configure: libpng"
#        exit 1
#    fi
#fi
